package net.es.lookup.scalability.testing;

import org.apache.log4j.Logger;
import org.ho.yaml.Yaml;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Coordinator {

    private static volatile boolean shutdown = false;
    private static int pending;

    private Logger LOG = Logger.getLogger(Coordinator.class);
//TODO: add input reading thread to look for shutdown command, then gracefully shutdown processes on remote hosts
    public static void main(String[] args) {

        String password = args[0];

        String configFile = "./lookup-service-scalability-framework/src/main/java/net/es/lookup/scalability/testing/config.yaml";
        //TODO: try configFile = "./config.yaml"

        Configuration.configure(configFile);

        pending = Configuration.clientHosts.size();

        try {
            System.out.println("Testing connection with sLS server...");
            Socket socket = new Socket(Configuration.slsServer, Configuration.port);

        } catch (IOException e) {

            System.out.println(e.getMessage());
            return;
        }

        MessengerPool messengerPool = new MessengerPool(Configuration.username, Configuration.clientHosts, Configuration.workingDir, Configuration.resultRepo, Configuration.clientProgram, Configuration.sshKeyFile, password);

        while (!shutdown && getPending() > 0) {

            synchronized (Coordinator.class) {

                try {

                    System.out.println("Waiting for messenger threads to finish work");
                    Coordinator.class.wait(4000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        System.out.println("Disconnecting from hosts");
        messengerPool.disconnect();
        System.out.println("Disconnected");

        OutputWriter.print(Configuration.resultRepo);
    }

    public static synchronized int getPending() {

        return pending;
    }

    public static synchronized void decrementPending() {

        if (--pending == 0) {

            setShutdownFlag(true);
        }
    }

    public static synchronized void setShutdownFlag(boolean value) {

        shutdown = value;
    }
}
